package com.openwater.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

/**
 * 
 * @author fuxp
 * @date 2012-6-8
 * @version 1.0
 * @since
 */
public class BitmapToolkit {

    public static Bitmap loadBitmapFromSDCard(String name) {
        try {
            File file = new File(name);
            if (file.exists()) {
                return null;
            }
            FileInputStream is = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap loadBitmapFromAssets(Resources res, String name) {
        try {
            InputStream is = res.getAssets().open(name);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * use Matrix scale the bitmap
     * 
     * @param bitmap
     * @param w
     *            width
     * @param h
     *            height
     * @return the new scale bitmap instance returned,and old bitmap is
     *         recycle();
     */
    public static Bitmap scaleImage(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width == w && height == h) {
            return bitmap;
        }
        float scaleWidth = ((float) w) / width;
        float scaleHeight = ((float) h) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap scaleImage = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.recycle();
        return scaleImage;
    }
}
